package com.nari.ncps.screen.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.CoalProdoperOsv;
import com.nari.ncps.screen.entity.coal.CoalProdoperOutput;
import com.nari.ncps.screen.mapper.coal.CoalProdoperOsvMapper;
import com.nari.ncps.screen.service.coal.CoalProdoperOsvService;
import com.nari.ncps.screen.vo.coal.CoalStrippingTrendVO;
import com.nari.ncps.screen.vo.coal.CoalStrippingUnitsVO;
import com.nari.ncps.screen.vo.coal.CoalStrippingVO;
import org.apache.commons.math3.stat.descriptive.summary.Sum;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产经营土岩剥离量表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalProdoperOsvServiceImpl extends ServiceImpl<CoalProdoperOsvMapper, CoalProdoperOsv> implements CoalProdoperOsvService {

    @Override
    public CoalStrippingVO getStripping(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }

        // 获取当前月份
        int currentMonth = LocalDate.now().getMonthValue();

        CoalStrippingVO vo = new CoalStrippingVO();

        // ============ 查询年度数据（date_type=0） ============

        // 查询自有年度数据（unit_type=0, date_type=0）
        LambdaQueryWrapper<CoalProdoperOsv> ownAnnualQuery = new LambdaQueryWrapper<>();
        ownAnnualQuery.eq(CoalProdoperOsv::getYear, year)
                      .eq(CoalProdoperOsv::getDateType, 0)
                      .eq(CoalProdoperOsv::getUnitType, 1)
                      .like(CoalProdoperOsv::getOrgCode, "50000%")  // 排除汇总数据
                    .orderByAsc(CoalProdoperOsv::getOrgCode);
        List<CoalProdoperOsv> ownAnnualDataList = this.list(ownAnnualQuery);

        // 求和处理
        if (ownAnnualDataList != null && !ownAnnualDataList.isEmpty()) {
            BigDecimal totalAnnualPlan = BigDecimal.ZERO;
            BigDecimal totalAnnualActual = BigDecimal.ZERO;
            BigDecimal totalAnnualCompletionRate = BigDecimal.ZERO;
            BigDecimal totalAnnualYoyRate = BigDecimal.ZERO;
            int count = 0;

            for (CoalProdoperOsv data : ownAnnualDataList) {
                totalAnnualPlan = totalAnnualPlan.add(data.getAnnualPlan() != null ? data.getAnnualPlan() : BigDecimal.ZERO);
                totalAnnualActual = totalAnnualActual.add(data.getAnnualActual() != null ? data.getAnnualActual() : BigDecimal.ZERO);
                if (data.getAnnualCompletionRate() != null) {
                    totalAnnualCompletionRate = totalAnnualCompletionRate.add(data.getAnnualCompletionRate());
                    count++;
                }
                totalAnnualYoyRate = totalAnnualYoyRate.add(data.getAnnualYoyRate() != null ? data.getAnnualYoyRate() : BigDecimal.ZERO);
            }

            vo.setOwnAnnualPlan(totalAnnualPlan);
            vo.setOwnAnnualActual(totalAnnualActual);

            // 重新计算完成率
            if (totalAnnualPlan.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal completionRate = totalAnnualActual
                        .divide(totalAnnualPlan, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setOwnAnnualCompletionRate(completionRate);
            } else {
                vo.setOwnAnnualCompletionRate(BigDecimal.ZERO);
            }

            vo.setOwnAnnualYoyRate(totalAnnualYoyRate);
        }

        // 查询外委年度数据（unit_type=1, date_type=0）
        LambdaQueryWrapper<CoalProdoperOsv> outsourceAnnualQuery = new LambdaQueryWrapper<>();
        outsourceAnnualQuery.eq(CoalProdoperOsv::getYear, year)
                            .eq(CoalProdoperOsv::getDateType, 0)
                            .eq(CoalProdoperOsv::getUnitType, 2);
        List<CoalProdoperOsv> outsourceAnnualDataList = this.list(outsourceAnnualQuery);

        // 求和处理
        if (outsourceAnnualDataList != null && !outsourceAnnualDataList.isEmpty()) {
            BigDecimal totalAnnualPlan = BigDecimal.ZERO;
            BigDecimal totalAnnualActual = BigDecimal.ZERO;
            BigDecimal totalAnnualYoyRate = BigDecimal.ZERO;

            for (CoalProdoperOsv data : outsourceAnnualDataList) {
                totalAnnualPlan = totalAnnualPlan.add(data.getAnnualPlan() != null ? data.getAnnualPlan() : BigDecimal.ZERO);
                totalAnnualActual = totalAnnualActual.add(data.getAnnualActual() != null ? data.getAnnualActual() : BigDecimal.ZERO);
                totalAnnualYoyRate = totalAnnualYoyRate.add(data.getAnnualYoyRate() != null ? data.getAnnualYoyRate() : BigDecimal.ZERO);
            }

            vo.setOutsourceAnnualPlan(totalAnnualPlan);
            vo.setOutsourceAnnualActual(totalAnnualActual);

            // 重新计算完成率
            if (totalAnnualPlan.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal completionRate = totalAnnualActual
                        .divide(totalAnnualPlan, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setOutsourceAnnualCompletionRate(completionRate);
            } else {
                vo.setOutsourceAnnualCompletionRate(BigDecimal.ZERO);
            }

            vo.setOutsourceAnnualYoyRate(totalAnnualYoyRate);
        }

        // ============ 查询月度数据（date_type=1） ============

        // 查询自有月度数据（unit_type=0, date_type=1, month=当前月）
        LambdaQueryWrapper<CoalProdoperOsv> ownMonthlyQuery = new LambdaQueryWrapper<>();
        ownMonthlyQuery.eq(CoalProdoperOsv::getYear, year)
                       .eq(CoalProdoperOsv::getMonth, currentMonth)
                       .eq(CoalProdoperOsv::getDateType, 1)
                       .eq(CoalProdoperOsv::getUnitType, 1);
        List<CoalProdoperOsv> ownMonthlyDataList = this.list(ownMonthlyQuery);

        // 求和处理
        if (ownMonthlyDataList != null && !ownMonthlyDataList.isEmpty()) {
            BigDecimal totalMonthlyPlan = BigDecimal.ZERO;
            BigDecimal totalMonthlyActual = BigDecimal.ZERO;
            BigDecimal totalMonthlyYoyRate = BigDecimal.ZERO;

            for (CoalProdoperOsv data : ownMonthlyDataList) {
                totalMonthlyPlan = totalMonthlyPlan.add(data.getMonthlyPlan() != null ? data.getMonthlyPlan() : BigDecimal.ZERO);
                totalMonthlyActual = totalMonthlyActual.add(data.getMonthlyActual() != null ? data.getMonthlyActual() : BigDecimal.ZERO);
                totalMonthlyYoyRate = totalMonthlyYoyRate.add(data.getMonthlyYoyRate() != null ? data.getMonthlyYoyRate() : BigDecimal.ZERO);
            }

            vo.setOwnMonthlyPlan(totalMonthlyPlan);
            vo.setOwnMonthlyActual(totalMonthlyActual);

            // 计算月完成率
            if (totalMonthlyPlan.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal monthlyCompletionRate = totalMonthlyActual
                        .divide(totalMonthlyPlan, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setOwnMonthlyCompletionRate(monthlyCompletionRate);
            } else {
                vo.setOwnMonthlyCompletionRate(BigDecimal.ZERO);
            }

            vo.setOwnMonthlyYoyRate(totalMonthlyYoyRate);
        }

        // 查询外委月度数据（unit_type=1, date_type=1, month=当前月）
        LambdaQueryWrapper<CoalProdoperOsv> outsourceMonthlyQuery = new LambdaQueryWrapper<>();
        outsourceMonthlyQuery.eq(CoalProdoperOsv::getYear, year)
                             .eq(CoalProdoperOsv::getMonth, currentMonth)
                             .eq(CoalProdoperOsv::getDateType, 1)
                             .eq(CoalProdoperOsv::getUnitType, 2);
        List<CoalProdoperOsv> outsourceMonthlyDataList = this.list(outsourceMonthlyQuery);

        // 求和处理
        if (outsourceMonthlyDataList != null && !outsourceMonthlyDataList.isEmpty()) {
            BigDecimal totalMonthlyPlan = BigDecimal.ZERO;
            BigDecimal totalMonthlyActual = BigDecimal.ZERO;
            BigDecimal totalMonthlyYoyRate = BigDecimal.ZERO;

            for (CoalProdoperOsv data : outsourceMonthlyDataList) {
                totalMonthlyPlan = totalMonthlyPlan.add(data.getMonthlyPlan() != null ? data.getMonthlyPlan() : BigDecimal.ZERO);
                totalMonthlyActual = totalMonthlyActual.add(data.getMonthlyActual() != null ? data.getMonthlyActual() : BigDecimal.ZERO);
                totalMonthlyYoyRate = totalMonthlyYoyRate.add(data.getMonthlyYoyRate() != null ? data.getMonthlyYoyRate() : BigDecimal.ZERO);
            }

            vo.setOutsourceMonthlyPlan(totalMonthlyPlan);
            vo.setOutsourceMonthlyActual(totalMonthlyActual);

            // 计算月完成率
            if (totalMonthlyPlan.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal monthlyCompletionRate = totalMonthlyActual
                        .divide(totalMonthlyPlan, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setOutsourceMonthlyCompletionRate(monthlyCompletionRate);
            } else {
                vo.setOutsourceMonthlyCompletionRate(BigDecimal.ZERO);
            }

            vo.setOutsourceMonthlyYoyRate(totalMonthlyYoyRate);
        }

        return vo;
    }

    @Override
    public List<CoalStrippingUnitsVO> getStrippingByUnits(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }

        // 查询各单位年度数据（year_month_type=0, unit_type IS NULL）
//        LambdaQueryWrapper<CoalProdoperOsv> query = new LambdaQueryWrapper<>();
//        query.eq(CoalProdoperOsv::getYear, year)
//                .eq(CoalProdoperOsv::getDateType, 0)  // 0表示年度数据
//                .like(CoalProdoperOsv::getOrgCode, "50000%")  // 排除汇总数据
//                .apply("1=1 GROUP BY bid, org_code, org_name")
//                .select("bid, org_code, org_name, " + "SUM(annual_plan) as totalAnnualPlan, " +
//                        "SUM(annual_actual) as totalAnnualActual")
//                .orderByAsc(CoalProdoperOsv::getOrgCode);



//        LambdaQueryWrapper<CoalProdoperOsv> query = new LambdaQueryWrapper<>();
//        query.select("bid, org_code, org_name, " +
//                        "SUM(annual_plan) as totalAnnualPlan, " +
//                        "SUM(annual_actual) as totalAnnualActual")
//                .eq(CoalProdoperOsv::getYear, year)
//                .eq(CoalProdoperOsv::getDateType, 0)
//                .likeRight(CoalProdoperOsv::getOrgCode, "50000")
//                .apply("1=1 GROUP BY bid, org_code, org_name")
//                .orderByAsc(CoalProdoperOsv::getOrgCode);

        // 查询各单位年度数据（year_month_type=0, unit_type IS NULL）
        QueryWrapper<CoalProdoperOsv> query = new QueryWrapper<>();
        query.select("org_code, org_name, " +
                        "SUM(annual_plan) as totalAnnualPlan, " +
                        "SUM(annual_actual) as totalAnnualActual")
                .eq("year", year)
                .eq("date_type", 0)  // 0表示年度数据
                .likeRight("org_code", "50000%")  // 排除汇总数据
                .groupBy("org_code, org_name")
                .orderByAsc("org_code");
        List<Map<String, Object>> result = this.listMaps(query);
        List<CoalStrippingUnitsVO> resultList = new ArrayList<>();
        for (Map<String, Object> map : result) {
            CoalStrippingUnitsVO vo = new CoalStrippingUnitsVO();
            vo.setUnitName((String) map.get("org_name"));
            vo.setUnitCode((String) map.get("org_code"));
            vo.setAnnualPlan((BigDecimal) map.get("totalAnnualPlan"));
            vo.setAnnualActual((BigDecimal) map.get("totalAnnualActual"));
            resultList.add(vo);
        }

        return resultList;

    }

    @Override
    public List<CoalStrippingTrendVO> getStrippingTrend(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();

        // 查询最近5年的年度数据（year_month_type=0, unit_code='TOTAL'）
        List<Integer> years = new ArrayList<>();
        for (int i = 4; i >=0; i--) {
            years.add(currentYear - i);
        }

        LambdaQueryWrapper<CoalProdoperOsv> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperOsv::getYear, years)
//             .eq(CoalProdoperOsv::getYearMonthType, false)
//             .eq(CoalProdoperOsv::getOrgCode, "TOTAL")
             .orderByAsc(CoalProdoperOsv::getYear);

        List<CoalProdoperOsv> dataList = this.list(query);

        // 转换为VO列表
        List<CoalStrippingTrendVO> resultList = new ArrayList<>();
        for (Integer myyear : years) {
            List<CoalProdoperOsv> collect = dataList.stream().filter(x -> x.getYear().equals(myyear) ).collect(Collectors.toList());

            BigDecimal planSum = collect.stream().map(CoalProdoperOsv::getAnnualPlan).filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal actSum = collect.stream().map(CoalProdoperOsv::getAnnualActual).filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal divide = null;
            if(planSum.compareTo(BigDecimal.ZERO) > 0 ) {
                 divide = actSum.divide(planSum, 4, RoundingMode.HALF_UP);
            }

            CoalStrippingTrendVO vo = new CoalStrippingTrendVO();
            vo.setYear(myyear);
            vo.setAnnualPlan(planSum);
            vo.setAnnualActual(actSum);
            vo.setAnnualCompletionRate(divide);
            resultList.add(vo);
        }
        
        return resultList;
    }

}
